
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>synchronized使用 - 交互式测验</title>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
        
        body {
          font-family: 'Noto Sans SC', sans-serif;
          background-color: #f4f7f9;
          color: #333;
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          margin: 0;
          padding: 20px;
          box-sizing: border-box;
        }
        
        .main-wrapper {
            position: relative;
            width: 100%;
            max-width: 900px; /* Wider to accommodate buttons */
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .quiz-container {
          background-color: #ffffff;
          border-radius: 16px;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
          width: 100%;
          max-width: 700px;
          overflow: hidden;
          z-index: 10;
        }

        .quiz-header {
          background-color: #4a90e2;
          color: white;
          padding: 20px 30px;
          text-align: center;
        }

        .quiz-header h1 {
          margin: 0;
          font-size: 24px;
          font-weight: 700;
        }
        
        .quiz-header p {
            margin: 5px 0 0;
            font-size: 14px;
            opacity: 0.9;
        }

        .quiz-body {
          padding: 30px;
        }

        .progress-bar {
            display: none; /* 隐藏进度条 */
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 5px;
            height: 10px;
            margin-bottom: 20px;
        }

        #progress-indicator {
            height: 100%;
            width: 0%;
            background-color: #4caf50;
            border-radius: 5px;
            transition: width 0.3s ease;
        }

        #question-container {
          margin-bottom: 20px;
        }

        #question-text {
          font-size: 18px;
          font-weight: 500;
          line-height: 1.6;
          margin-bottom: 25px;
        }

        .options-list {
          list-style: none;
          padding: 0;
          margin: 0;
        }

        .option-item {
          background-color: #f8f9fa;
          border: 1px solid #dee2e6;
          border-radius: 8px;
          padding: 15px;
          margin-bottom: 12px;
          cursor: pointer;
          transition: background-color 0.2s ease, border-color 0.2s ease;
        }

        .option-item:hover {
          background-color: #e9ecef;
        }
        
        .option-item.selected {
            background-color: #d1e7fd;
            border-color: #4a90e2;
        }

        .quiz-footer {
          padding: 20px 30px;
          display: flex;
          justify-content: space-between; /* 将按钮分布在两侧 */
          align-items: center;
          min-height: 65px; /* Reserve space */
        }

        .nav-btn {
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 8px;
          padding: 10px 20px;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.2s ease, transform 0.2s ease;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        #next-btn {
            background-color: #28a745;
        }

        .nav-btn:hover {
          background-color: #357abd;
          transform: scale(1.05);
        }
        
        .nav-btn:disabled {
            background-color: #a0c3e8;
            cursor: not-allowed;
            opacity: 0.7;
        }

        #result-container {
            border-top: 1px solid #eee;
        }
        
        .result-box {
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .result-box.correct {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .result-box.incorrect {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .result-box h3 {
            margin-top: 0;
        }

        .explanation-text {
            margin-top: 15px;
            line-height: 1.7;
        }
        
        .source-text {
            font-style: italic;
            font-size: 14px;
            margin-top: 15px;
            color: #555;
        }

        
        .final-score-container {
            padding: 40px;
            text-align: center;
        }
        .final-score-container h2 {
            margin-top: 0;
            margin-bottom: 30px;
        }
        .score-summary {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 40px;
            flex-wrap: wrap;
        }
        .score-card {
            background-color: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            width: 180px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #e9ecef;
        }
        .score-card h3 {
            margin: 0 0 10px;
            font-size: 16px;
            font-weight: 500;
            color: #555;
        }
        .score-card p {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            color: #333;
        }
        .score-details table {
            width: 100%;
            font-size: 16px;
        }
        .score-details td {
            padding: 4px 0;
        }
        .score-details td:last-child {
            text-align: right;
            font-weight: 700;
        }
        .report-actions button {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 12px 25px;
            font-size: 16px;
            cursor: pointer;
            margin: 0 10px;
            transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
        }
        .report-actions button:hover {
            background-color: #f1f1f1;
            border-color: #bbb;
            transform: translateY(-2px);
        }
        .report-actions button.primary {
            background-color: #28a745;
            color: white;
            border-color: #28a745;
        }
        .report-actions button.primary:hover {
            background-color: #218838;
        }
        
        .hint-container {
            background-color: #e0f7fa;
            border: 1px solid #b2ebf2;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            color: #006064;
            font-size: 15px;
            line-height: 1.6;
            display: none; /* 默认隐藏 */
        }
      </style>
    </head>
    <body>
      <div class="main-wrapper">
          <div class="quiz-container">
            <div class="quiz-header">
              <h1>synchronized使用 - 交互式测验</h1>
              <p>检验你对文档内容的理解程度</p>
            </div>
            <div id="quiz-content">
                <div class="quiz-body">
                    <div class="progress-bar">
                        <div id="progress-indicator"></div>
                    </div>
                    <div id="question-container">
                      <p id="question-text"></p>
                      <ul class="options-list" id="options-list"></ul>
                    </div>
                    <div id="result-container"></div>
                    <div id="hint-container" class="hint-container"></div>
                </div>
                <div class="quiz-footer" id="quiz-footer">
                  <button id="prev-btn" class="nav-btn">上一题</button>
                  <button id="hint-btn" class="nav-btn" style="background-color: #ffc107; color: #333; box-shadow: 0 4px 12px rgba(255,193,7,0.3);">提示</button>
                  <button id="next-btn" class="nav-btn">下一题</button>
                </div>
            </div>
          </div>
      </div>

      <script>
        const quizData = [
  {
    "question": "当 `synchronized` 关键字被用于修饰一个静态方法时，它获取的是哪种类型的锁？",
    "options": [
      "对象级别的锁，只对当前类的特定实例生效",
      "一个独立的 `Lock` 对象，需要手动创建",
      "类级别的锁，对该类的所有实例都生效",
      "无锁，静态方法无法被同步"
    ],
    "correctAnswerIndex": 2,
    "explanation": "`synchronized` 修饰静态方法时，获取的是该类（Class对象）本身的锁。这意味着无论创建了多少个该类的实例，在任何时刻都只有一个线程能够执行该类的任何一个同步静态方法，因为它们共享同一把类锁。",
    "source": "文档中「锁的粒度」部分的「类级别的锁」",
    "hint": "思考一下，静态方法是属于类还是属于对象？这决定了锁的目标。"
  },
  {
    "question": "根据文档，`synchronized` 关键字除了保证操作的互斥性之外，还提供了哪个重要的内存一致性保证？",
    "options": [
      "操作的原子性（Atomicity）",
      "内存可见性（Memory Visibility）",
      "指令的有序性（Ordering）",
      "数据的持久性（Durability）"
    ],
    "correctAnswerIndex": 1,
    "explanation": "文档明确指出，`synchronized` 关键字除了提供互斥性外，还提供了内存可见性。这意味着当一个线程释放锁时，它对共享变量所做的所有修改都会被刷新到主内存，确保后续获得该锁的线程能够看到这些最新的修改。",
    "source": "文档中「实现原理」部分的「内存可见性」",
    "hint": "考虑当一个线程修改了数据后，其他线程如何才能看到这个修改？"
  },
  {
    "question": "在并发编程中，为了提高性能，文档建议如何控制 `synchronized` 的锁粒度？",
    "options": [
      "锁的粒度应该尽可能大，最好是同步整个方法，以确保绝对安全。",
      "锁的粒度应该尽可能小，只对必要的、修改共享资源的代码块进行同步。",
      "总是使用静态同步方法，因为类锁最安全。",
      "避免使用同步代码块，因为它比同步方法开销更大。"
    ],
    "correctAnswerIndex": 1,
    "explanation": "文档在多个章节中强调，为了提升并发性能，应尽量减小锁的粒度。只同步必要的代码片段可以减少线程竞争和阻塞的时间，从而提高程序的并发度。对整个方法进行同步可能会导致不必要的性能下降。",
    "source": "文档中「并发编程注意事项」部分的「锁的粒度控制」",
    "hint": "思考一下，如果一个很长的方法里只有一行业务代码需要同步，锁住整个方法会带来什么影响？"
  },
  {
    "question": "文档中提到的 `synchronized` 的实现原理是基于什么机制？",
    "options": [
      "操作系统提供的信号量（Semaphore）机制",
      "Java对象头中的标志位和每个对象关联的监视器锁（Monitor Lock）",
      "一种名为“比较并交换”（CAS）的无锁算法",
      "依赖于 `volatile` 关键字实现的轻量级锁"
    ],
    "correctAnswerIndex": 1,
    "explanation": "文档的核心原理解释是，`synchronized` 的同步机制是基于每个Java对象都拥有的一个监视器锁（Monitor Lock）来实现的。线程在进入同步代码时会尝试获取这个锁，而锁的状态信息就存储在对象的头部（Object Header）中。",
    "source": "文档中「实现原理」部分的「对象锁和监视器锁」与「对象头中的标志位」",
    "hint": "文档中提到 “每个Java对象都可以作为一个锁”，这个锁具体是什么？"
  },
  {
    "question": "与 `synchronized` 相比，`java.util.concurrent.locks.Lock` 接口提供的一个显著优势是什么？",
    "options": [
      "`Lock` 接口是自动释放锁的，无需开发者手动处理。",
      "`Lock` 接口的性能在任何情况下都优于 `synchronized`。",
      "`Lock` 接口是不可重入的，可以防止逻辑错误。",
      "`Lock` 接口提供了可中断的获取锁方式和可选择的公平性策略。"
    ],
    "correctAnswerIndex": 3,
    "explanation": "文档对比部分明确指出，`Lock` 锁比 `synchronized` 更加灵活。例如，它支持可中断的锁获取（`lockInterruptibly()`），允许线程在等待锁时响应中断；并且可以创建公平锁，保证等待时间最长的线程能优先获得锁，而 `synchronized` 是非公平的。",
    "source": "文档中「与Lock锁对比比较」部分的「可中断性」与「公平性」",
    "hint": "当一个线程在苦等一个锁时，如果希望它能放弃等待去做别的事情，`synchronized` 能做到吗？"
  },
  {
    "question": "在编写同步代码块时，例如 `synchronized(lockObject) { ... }`，选择 `lockObject` 的最佳实践是什么？",
    "options": [
      "使用字符串字面量，例如 `\"lock\"`，因为它简单易懂。",
      "使用一个私有的、`final` 的 `Object` 实例作为锁对象。",
      "使用当前类的 `this` 引用，这样可以与同步方法共用一把锁。",
      "使用一个 `Integer` 或 `Boolean` 类型的变量，因为它们占用内存小。"
    ],
    "correctAnswerIndex": 1,
    "explanation": "虽然文档中的示例使用了 `private Object lock = new Object();`，这是业界公认的最佳实践。使用一个私有的、final的、专门用于锁的对象可以避免外部代码无意中获取到同一个锁，从而引发不可预料的并发问题。使用`this`会扩大锁的影响范围，而使用字符串字面量或基本类型的包装类可能会导致JVM范围内的多个不相关同步块共享同一个锁，引发严重问题。",
    "source": "文档中「使用方法」部分的「代码块的同步」示例代码",
    "hint": "思考如何让锁的作用域被精确控制，不被外部意外干扰。"
  },
  {
    "question": "当多个线程因竞争同一个 `synchronized` 锁而被阻塞时，以下哪个描述是正确的？",
    "options": [
      "等待时间最长的线程将保证第一个获取到锁。",
      "线程会立即抛出异常并终止。",
      "线程将进入阻塞状态，直到锁被释放，且无法保证获取锁的顺序。",
      "JVM会自动为每个线程创建一个新的锁来避免阻塞。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "文档在对比 `synchronized` 和 `Lock` 时提到，`synchronized` 是一种非公平锁。这意味着当锁被释放时，JVM会从等待队列中唤醒一个线程，但并不保证是等待时间最长的那个线程。因此，线程会阻塞等待，且获取顺序是不确定的。",
    "source": "文档中「与Lock锁对比比较」部分的「公平性」",
    "hint": "`synchronized` 是公平的还是非公平的？这决定了线程被唤醒的顺序。"
  }
];
        console.log("Quiz Data:", JSON.parse(JSON.stringify(quizData))); // 添加这行用于调试，以可展开的JSON格式输出
        
        let currentQuestionIndex = 0;
        let score = 0;
        // 存储每个问题的回答状态
        const userAnswers = new Array(quizData.length).fill(null); 

        const questionTextEl = document.getElementById('question-text');
        const optionsListEl = document.getElementById('options-list');
        const resultContainerEl = document.getElementById('result-container');
        const quizContentEl = document.getElementById('quiz-content');
        const progressIndicatorEl = document.getElementById('progress-indicator');
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const hintBtn = document.getElementById('hint-btn');
        const hintContainerEl = document.getElementById('hint-container');

        function loadQuestion() {
          resultContainerEl.innerHTML = '';
          optionsListEl.innerHTML = '';
          hintContainerEl.style.display = 'none'; // 隐藏提示
          
          if (currentQuestionIndex >= quizData.length) {
            showFinalScore();
            return;
          }

          updateProgress();

          const currentQuestion = quizData[currentQuestionIndex];
          questionTextEl.textContent = `(${currentQuestionIndex + 1}/${quizData.length}) ${currentQuestion.question}`;
          
          currentQuestion.options.forEach((optionText, index) => {
            const li = document.createElement('li');
            li.className = 'option-item';
            li.textContent = optionText;
            li.dataset.index = index; // Store index in a data attribute
            // 如果这道题已经回答过，恢复状态
            if (userAnswers[currentQuestionIndex] !== null) {
                if (index === userAnswers[currentQuestionIndex]) {
                    li.classList.add('selected');
                }
            }
            optionsListEl.appendChild(li);
          });

          // 如果已经回答过，直接显示结果
          if (userAnswers[currentQuestionIndex] !== null) {
              const isCorrect = userAnswers[currentQuestionIndex] === currentQuestion.correctAnswerIndex;
              showResult(isCorrect, currentQuestion);
          }
          
          updateNavigationButtons();
          updateProgress();
        }

        function selectOption(optionIndex) {
            userAnswers[currentQuestionIndex] = optionIndex;
            const currentQuestion = quizData[currentQuestionIndex];
            const isCorrect = optionIndex === currentQuestion.correctAnswerIndex;

            // 重新计算分数
            score = userAnswers.reduce((acc, answer, index) => {
                return answer === quizData[index].correctAnswerIndex ? acc + 1 : acc;
            }, 0);

            showResult(isCorrect, currentQuestion);
            updateNavigationButtons();
        }
        
        function updateProgress() {
            const answeredQuestions = userAnswers.filter(answer => answer !== null).length;
            const progressPercentage = (answeredQuestions / quizData.length) * 100;
            progressIndicatorEl.style.width = `${progressPercentage}%`;
        }
        
        function updateNavigationButtons() {
            prevBtn.style.display = 'block';
            nextBtn.style.display = 'block';
            hintBtn.style.display = 'block'; // 显示提示按钮

            prevBtn.disabled = currentQuestionIndex === 0;
            nextBtn.disabled = false; // 最后一题时，下一题按钮不禁用，而是用于显示报告
            nextBtn.textContent = (currentQuestionIndex === quizData.length - 1) ? '查看报告' : '下一题';
            
            // 如果当前问题没有提示，则禁用提示按钮并隐藏提示内容
            if (!quizData[currentQuestionIndex].hint) {
                hintBtn.disabled = true;
                hintContainerEl.style.display = 'none';
                hintContainerEl.textContent = ''; // 清除旧的提示内容
            } else {
                hintBtn.disabled = false;
            }
        }

        function showResult(isCorrect, questionData) {
            resultContainerEl.innerHTML = ''; // 清空之前的结果
            const resultBox = document.createElement('div');
            resultBox.className = `result-box ${isCorrect ? 'correct' : 'incorrect'}`;
            
            let html = `<h3>${isCorrect ? '回答正确！' : '回答错误'}</h3>`;
            if (!isCorrect) {
                html += `<p><strong>正确答案是：</strong> ${questionData.options[questionData.correctAnswerIndex]}</p>`;
            }
            html += `<div class="explanation-text">${questionData.explanation}</div>`;
            html += `<div class="source-text">来源: ${questionData.source}</div>`;
            
            resultBox.innerHTML = html;
            resultContainerEl.appendChild(resultBox);

            // 禁用所有选项的点击事件，并高亮正确/错误答案
            Array.from(optionsListEl.children).forEach((child, index) => {
                child.style.pointerEvents = 'none';
                // 高亮正确答案
                if (index === questionData.correctAnswerIndex) {
                    child.classList.add('correct'); // 需要添加CSS样式
                    child.style.backgroundColor = '#d4edda';
                    child.style.borderColor = '#c3e6cb';
                }
                // 如果选错了，高亮错误选项
                if (!isCorrect && index === userAnswers[currentQuestionIndex]) {
                    child.classList.add('incorrect'); // 需要添加CSS样式
                    child.style.backgroundColor = '#f8d7da';
                    child.style.borderColor = '#f5c6cb';
                }
            });
        }

        function goToNextQuestion() {
            if (currentQuestionIndex < quizData.length - 1) {
                currentQuestionIndex++;
                loadQuestion();
            } else {
                showFinalScore();
            }
        }

        function goToPreviousQuestion() {
            if (currentQuestionIndex > 0) {
                currentQuestionIndex--;
                loadQuestion();
            }
        }
        
        function showHint() {
            const currentQuestion = quizData[currentQuestionIndex];
            if (currentQuestion.hint) {
                hintContainerEl.textContent = currentQuestion.hint;
                hintContainerEl.style.display = 'block';
            } else {
                hintContainerEl.style.display = 'none';
            }
        }

        function showFinalScore() {
            document.querySelector('.quiz-body').style.display = 'none';
            document.getElementById('quiz-footer').style.display = 'none';

            const correctCount = score;
            const totalQuestions = quizData.length;
            const answeredCount = userAnswers.filter(a => a !== null).length;
            const wrongCount = answeredCount - correctCount;
            const skippedCount = totalQuestions - answeredCount;
            const accuracy = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0;
            const errorRate = totalQuestions > 0 ? Math.round((wrongCount / totalQuestions) * 100) : 0;

            const finalScoreHtml =
                '<div class="final-score-container">' +
                '<h2>答题报告</h2>' +
                '<div class="score-summary">' +
                '<div class="score-card">' +
                '<h3>得分</h3>' +
                '<p>' + correctCount + ' / ' + totalQuestions + '</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>正确率</h3>' +
                '<p>' + accuracy + '%</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>错误率</h3>' +
                '<p>' + errorRate + '%</p>' +
                '</div>' +
                '<div class="score-card score-details">' +
                '<table>' +
                '<tr><td>正确</td><td>' + correctCount + '</td></tr>' +
                '<tr><td>错误</td><td>' + wrongCount + '</td></tr>' +
                '<tr><td>未答</td><td>' + skippedCount + '</td></tr>' +
                '</table>' +
                '</div>' +
                '</div>' +
                '<div class="report-actions">' +
                '<button id="review-btn">回顾测验</button>' +
                '<button class="primary" onclick="location.reload()">再试一次</button>' +
                '</div>' +
                '</div>';

            let reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }
            quizContentEl.insertAdjacentHTML('beforeend', finalScoreHtml);
            document.getElementById('review-btn').addEventListener('click', reviewQuiz);
        }

        function reviewQuiz() {
            const reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }

            document.querySelector('.quiz-body').style.display = 'block';
            document.getElementById('quiz-footer').style.display = 'flex';
            
            currentQuestionIndex = 0;
            loadQuestion();
            updateNavigationButtons(); // Ensure nav buttons are correctly displayed
        }

        // Event Delegation for options
        optionsListEl.addEventListener('click', (event) => {
            if (event.target && event.target.matches('li.option-item')) {
                // Check if the question has already been answered
                if (userAnswers[currentQuestionIndex] === null) {
                    const selectedIndex = parseInt(event.target.dataset.index, 10);
                    selectOption(selectedIndex);
                }
            }
        });

        prevBtn.addEventListener('click', goToPreviousQuestion);
        nextBtn.addEventListener('click', goToNextQuestion);
        hintBtn.addEventListener('click', showHint);
        
        // 初始加载
        loadQuestion();
      </script>
    </body>
    </html>
  